import storage from 'good-storage'
import PORTRAIT_DEFAULT from 'assets/image/portrait-default.png'
import Dictionary from 'assets/js/dictionary'

const TOKEN_KEY = '__token__'
const USERINFO_KEY = '__userInfo__'
const SEARCH_MAX_LEN = 5

export function getToken() {
  return storage.get(TOKEN_KEY) ? storage.get(TOKEN_KEY) : ''
}

export function cacheToken(str) {
  storage.set(TOKEN_KEY, str)
  return str
}

export function clearToken(str) {
  storage.remove(TOKEN_KEY)
}

export function getUserInfo() {
  return storage.get(USERINFO_KEY) ? storage.get(USERINFO_KEY) : ''
}

export function cacheUserInfo(data) {
  storage.set(USERINFO_KEY, data)
  return data
}

export function updateUserVIP() {
  let userInfo = getUserInfo()
  if (userInfo) {
    userInfo.vipFlag = 1
    cacheUserInfo(userInfo)
  }
}

export function clearUserInfo() {
  storage.remove(USERINFO_KEY)
}

export function getAvatar() {
  return PORTRAIT_DEFAULT
}

function insertArray(arr, val, compare, maxLen) {
  const index = arr.findIndex(compare)
  if (index === 0) {
    return
  }
  if (index > 0) {
    arr.splice(index, 1)
  }
  arr.unshift(val)
  if (maxLen && arr.length > maxLen) {
    arr.pop()
  }
}

function deleteFromArray(arr, compare) {
  const index = arr.findIndex(compare)
  if (index > -1) {
    arr.splice(index, 1)
  }
}

export function addHistory(historyItem) {
  var module = historyItem.module
  var key = `${module}_history`
  let historyList = storage.get(key, [])
  insertArray(
    historyList,
    historyItem.data,
    item => {
      return item.name === historyItem.data.name
    },
    SEARCH_MAX_LEN
  )

  storage.set(key, historyList)
  return {
    module,
    historyList
  }
}

export function deleteHistory(historyItem) {
  var module = historyItem.module
  var key = `${module}_history`
  let historyList = storage.get(key, [])

  deleteFromArray(historyList, item => {
    return item.name === historyItem.data.name
  })
  storage.set(key, historyList)
  return {
    module,
    historyList
  }
}

export function clearHistory(module) {
  storage.remove(`${module}_history`)
  return {
    module,
    historyList: []
  }
}

export function loadHistoryList(module) {
  return storage.get(`${module}_history`, [])
}